package sqlite

import (
	"errors"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"lht-go-plugins/LhtLog"
	"lht-go-plugins/LhtSettings"
	"lht-go-plugins/internal/core"
	"os"
	"path/filepath"
)

type SqlitePlugin struct {
	*core.BasePlugin
	conf LhtSettings.SqliteConfig // 稍后会在 LhtSettings 加这个结构体
	db   *gorm.DB
}

func NewSqlitePlugin() *SqlitePlugin {
	return &SqlitePlugin{
		BasePlugin: core.NewBasePlugin("sqlite", 2002),
	}
}

func (s *SqlitePlugin) Init(cfg any) error {
	conf, ok := cfg.(*LhtSettings.SqliteConfig)
	if !ok || conf == nil || conf.Path == "" {
		return errors.New("invalid or missing sqlite config")
	}
	s.conf = *conf
	return nil
}

func (s *SqlitePlugin) Start() error {
	// 确保数据库目录存在
	dir := filepath.Dir(s.conf.Path) // 这里用 filepath.Dir 是正确的
	if dir != "." && dir != "" {
		if err := os.MkdirAll(dir, 0755); err != nil { // ←← 用 os.MkdirAll
			return fmt.Errorf("create sqlite dir failed: %w", err)
		}
	}

	db, err := gorm.Open(sqlite.Open(s.conf.Path+"?cache=shared&mode=rwc"), &gorm.Config{
		SkipDefaultTransaction: true,
		CreateBatchSize:        100,
	})
	if err != nil {
		LhtLog.Error("SQLite open failed", zap.String("path", s.conf.Path), zap.Error(err))
		return err
	}

	// 自动建表
	if err := db.AutoMigrate(&OCMessage{}, &SignalMessage{}); err != nil {
		LhtLog.Error("SQLite AutoMigrate failed", zap.Error(err))
		return err
	}

	s.db = db
	LhtLog.Info("SQLite connected", zap.String("path", s.conf.Path))

	return nil
}

// 核心处理函数
func (s *SqlitePlugin) handleData(data []byte) {
	fmt.Printf("[sqlite] recv raw data len=%d\n", len(data))
}
func (s *SqlitePlugin) Save(msg any) error {
	if s.db == nil {
		return errors.New("db not ready")
	}
	return s.db.Create(msg).Error
}
func (s *SqlitePlugin) Stop() error {
	if s.db != nil {
		if sqlDB, err := s.db.DB(); err == nil {
			return sqlDB.Close()
		}
	}
	return nil
}
